package me.ingxin.android.permission2.task

import android.content.Context
import me.ingxin.android.permission2.PERMISSION_ACCESS_BACKGROUND_LOCATION
import me.ingxin.android.permission2.permissionGranted
import me.ingxin.android.permission2.request.Request
import me.ingxin.android.permission2.request.Task
import me.ingxin.android.permission2.request.TaskChain
import me.ingxin.android.permission2.specialPermissionGranted
import me.ingxin.android.permission2.strategy.ReasonStrategy

/**
 * Created on 2023/7/6 by yin
 * 检查权限获取情况，处理被系统直接拒绝权限而没有显示系统权限弹窗的权限
 */
internal class FinallyTask(private val checker: PermissionResultChecker) : Task {
    override fun runTask(chain: TaskChain, request: Request) {
        val reasonStrategy = request.reasonStrategy
        if (reasonStrategy == ReasonStrategy.After) {
            val deniedList = getRetryPermissionList(
                chain.context, request.normalPermissions, request.specialPermissions
            )
            if (deniedList.isNotEmpty()) {
                resetChain(chain, request, reasonStrategy)
                return
            }
        }
        checker.check(chain.context, request.normalPermissions, request.specialPermissions)
    }

    /**
     * 从任务链头部重新执行
     */
    private fun resetChain(chain: TaskChain, request: Request, oldReasonStrategy: ReasonStrategy) {
        val strategy = when (oldReasonStrategy) {
            //设置成请求前显示理由，在次执行任务链
            ReasonStrategy.After -> ReasonStrategy.Before
            else -> throw IllegalArgumentException("oldReasonStrategy $oldReasonStrategy")
        }
        chain.proceedHead(request.newBuilder().reasonStrategy(strategy).build())
    }

    private fun getRetryPermissionList(
        context: Context, normalPermissions: List<String>, specialPermissions: List<String>
    ): List<String> {
        val list = ArrayList<String>()
        normalPermissions.forEach {
            if (!context.permissionGranted(it)) {
                list.add(it)
            }
        }

        specialPermissions.forEach {
            //只有后台定位这个特殊权限，才需要重新提示，其余提示没有意义
            if (PERMISSION_ACCESS_BACKGROUND_LOCATION == it && !context.specialPermissionGranted(it)) {
                list.add(it)
            }
        }
        return list
    }

}